import { Component, OnInit, ChangeDetectionStrategy, Input } from '@angular/core';
import { Subject } from 'rxjs';
import { v4 } from 'uuid';
import { merge, map } from 'ramda';
import { ForminData, Control, ControlType, DashboardType } from '../../dashboard/dashboard-model';

@Component({
  selector: 'app-renderer-main',
  templateUrl: './renderer-main.component.html',
  styleUrls: ['./renderer-main.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class RendererMainComponent implements OnInit {
  
  destroy$ = new Subject();

  @Input() set data(data: ForminData) {
    if (!data) {
      return;
    }

    const { templateId, items } = data;

    this.templateId = templateId;
    this.items = this.modifyControls(items);
  }

  templateId: string;

  items: Control[];

  dashboardType = DashboardType.Renderer;

  constructor() { }

  ngOnInit() {
  }

  addDefaultControlConfig(control: Control) {
    let config: any = { 
      uuid: v4(),
      minItemCols: 3,
      maxItemCols: 12,
    };

    switch (control.type) {
      case ControlType.Header:
        Object.assign(config, {
          maxItemRows: 1,
          minItemRows: 1,
        });
        break;
      case ControlType.Hr:
        Object.assign(config, {
          maxItemRows: 1,
          minItemRows: 1,
        });
        break;
      case ControlType.Text:
        Object.assign(config, {
          minItemRows: 2,
          maxItemRows: 2,
        });
        break;
      case ControlType.Textarea:
        Object.assign(config, {
          minItemRows: 3,
        });
        break;
      case ControlType.Radio:
        Object.assign(config, {
          minItemRows: 2,
          maxItemRows: 2,
        });
        break;
      case ControlType.Checkbox:
        Object.assign(config, {
          minItemRows: 3,
        });
        break;
      case ControlType.Switch:
        Object.assign(config, {
          minItemRows: 2,
          maxItemRows: 2,
        });
        break;
      case ControlType.Datetime:
        Object.assign(config, {
          minItemRows: 2,
          maxItemRows: 2,
        });
        break;
      default:
        break;
    }

    return merge(config, control);
  }

  modifyControls(controls: any) {
    return map(control => {
      return this.addDefaultControlConfig(control);
    }, controls)
  }

}
